// Package audioplayer 提供统一的音频播放接口和实现
package factory

import (
	"fmt"

	"gitee.com/rw555/fdsmastergo/pkg/audioplayer"
	"gitee.com/rw555/fdsmastergo/pkg/audioplayer/adapter"
)

// 用于创建特定适配器播放器的工厂函数类型
type AdapterFactoryFunc func(config *audioplayer.Config) (audioplayer.AudioPlayer, error)

// PlayerFactory 播放器工厂，负责创建不同适配器的播放器实例
type PlayerFactory struct {
	// 适配器注册表，键为适配器类型，值为创建函数
	adapters map[audioplayer.AdapterType]AdapterFactoryFunc
	// 默认配置
	config *audioplayer.Config
}

// NewPlayerFactory 创建一个新的播放器工厂
func NewPlayerFactory(config *audioplayer.Config) *PlayerFactory {
	return &PlayerFactory{
		adapters: make(map[audioplayer.AdapterType]AdapterFactoryFunc),
		config:   config,
	}
}

// RegisterAdapter 注册适配器及其创建函数
func (f *PlayerFactory) RegisterAdapter(adapterType audioplayer.AdapterType, factoryFunc AdapterFactoryFunc) {
	f.adapters[adapterType] = factoryFunc
}

// CreatePlayer 使用指定的适配器类型创建播放器
func (f *PlayerFactory) CreatePlayer(adapterType audioplayer.AdapterType) (audioplayer.AudioPlayer, error) {
	// 查找适配器创建函数
	factoryFunc, exists := f.adapters[adapterType]
	if !exists {
		return nil, fmt.Errorf("不支持的适配器类型: %s", adapterType)
	}

	// 使用工厂函数创建播放器
	return factoryFunc(f.config)
}

// RegisterAdapters 注册所有支持的适配器到工厂
func RegisterAdapters(factory *PlayerFactory) {
	// 注册虚拟播放器适配器
	factory.RegisterAdapter(audioplayer.AdapterVirtual, func(config *audioplayer.Config) (audioplayer.AudioPlayer, error) {
		return adapter.NewVirtualPlayer()
	})

	// 注册aplay适配器
	factory.RegisterAdapter(audioplayer.AdapterAplay, func(config *audioplayer.Config) (audioplayer.AudioPlayer, error) {
		return adapter.NewAplayPlayer(config)
	})

	// 注册mpg123适配器
	factory.RegisterAdapter(audioplayer.AdapterMpg123, func(config *audioplayer.Config) (audioplayer.AudioPlayer, error) {
		return adapter.NewMPG123Player(config)
	})

	// 其他适配器后续添加
	//factory.RegisterAdapter(audioplayer.AdapterGolib, golib.NewPlayer)
	//factory.RegisterAdapter(audioplayer.AdapterAlsa, alsa.NewPlayer)
	//factory.RegisterAdapter(audioplayer.AdapterNetwork, network.NewPlayer)
}

// CreateAudioPlayer 创建一个配置好的音频播放器
func CreateAudioPlayer(config *audioplayer.Config) (audioplayer.AudioPlayer, error) {
	factory := NewPlayerFactory(config)

	RegisterAdapters(factory)

	// 根据配置选择适配器
	var err error
	var audioPlayer audioplayer.AudioPlayer
	if config.AdapterType != "" {
		audioPlayer, err = factory.CreatePlayer(config.AdapterType)
	} else {
		audioPlayer, err = factory.CreatePlayer(audioplayer.AdapterVirtual)
	}

	if err != nil {
		return nil, err
	}

	// 初始化音频播放器
	if err = audioPlayer.Initialize(); err != nil {
		return nil, err
	}

	return audioPlayer, nil
}
